<?php

/** 
 * @Author: 李红雨 - RainLee <rainlee1990@yeah.net>
 * @Date: 2022-04-24 21:09:00
 * @LastEditors: 李红雨 - RainLee <rainlee1990@yeah.net>
 * @LastEditTime: 2022-07-01 22:46:56
 * @Description: File Description
 */

declare(strict_types=1);

namespace rainlee\authn\middleware;

use Exception;
use Firebase\JWT\ExpiredException;
use rainlee\authn\exception\UnauthorizedException;
use rainlee\authn\facade\Authn;

class Authentication
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 登录认证
        try {
            Authn::guard(app('http')->getName())->check();
        } catch (UnauthorizedException $e) {
            return json([
                'errcode' => 4011,
                'message' => 'Unauthorized'
            ]);
        } catch (ExpiredException $e) { // token 过期异常
            return json([
                'errcode' => 4012,
                'message' => $e->getMessage()
            ]);
        } catch (Exception $e) {
            return json([
                'errcode' => 1,
                'message' => $e->getMessage()
            ]);
        }
        return $next($request);
    }
}
